package cn.bob.product.service.impl;

import cn.bob.basic.config.BussinessException;
import cn.bob.basic.query.BaseQuery;
import cn.bob.basic.utils.BaiduAuditUtils;
import cn.bob.basic.utils.CodeGenerateUtils;
import cn.bob.basic.utils.FreemarkerUtil;
import cn.bob.basic.utils.PageList;
import cn.bob.order.domain.OrderProduct;
import cn.bob.order.mapper.OrderProductMapper;
import cn.bob.order.query.OrderProductQuery;
import cn.bob.org.domain.Shop;
import cn.bob.org.mapper.ShopMapper;
import cn.bob.product.domain.Product;
import cn.bob.product.domain.ProductDetail;
import cn.bob.product.domain.ProductOnlineAuditLog;
import cn.bob.product.domain.ProductStaycheck;
import cn.bob.product.mapper.ProductDetailMapper;
import cn.bob.product.mapper.ProductMapper;
import cn.bob.product.mapper.ProductOnlineAuditLogMapper;
import cn.bob.product.mapper.ProductStaycheckMapper;
import cn.bob.product.service.IProductService;
import cn.bob.basic.service.impl.BaseServiceImpl;
import cn.bob.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bob
 * @since 2022-11-03
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Autowired
    private ProductOnlineAuditLogMapper productOnlineAuditLogMapper;

    @Autowired
    private OrderProductMapper orderProductMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ProductStaycheckMapper productStaycheckMapper;

    @Autowired
    private UserMapper userMapper;
    @Value("${pagedir}")
    private String path;


    @Override
    public void add(Product product) {
        super.add(product);
        ProductDetail productDetail = new ProductDetail();
        productDetail.setIntro(product.getDetail().getIntro());
        productDetail.setOrderNotice(product.getDetail().getOrderNotice());
        productDetail.setProductId(product.getId());
        productDetailMapper.add(productDetail);
    }

    @Override
    public Product bydetail(Long id) {
        return productMapper.bydetail(id);
    }

    @Override
    public void onsaleProduct(List<Long> ids) {
        //批量上架操作 查询下架状态
        Date date = new Date();
        List<Product> products = getProducts(ids, 0L);
        StringBuilder sb = new StringBuilder();
        ProductOnlineAuditLog productOnlineAuditLog = new ProductOnlineAuditLog();
        try {
            checkData(ids,date, products, sb, productOnlineAuditLog);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void checkData(List<Long> ids,Date date, List<Product> products, StringBuilder sb, ProductOnlineAuditLog productOnlineAuditLog) throws IOException {
        for (Product product : products) {
            //验证图片和名字的合规
            if (!BaiduAuditUtils.TextCensor(product.getName())) {
                sb.append("当前服务名字违规，服务名字是:").append(product.getResources()).append(";");
            }
            if (StringUtils.isNotBlank(product.getResources())) {
                String[] split = null;
                if (product.getResources().indexOf(",") == -1) {
                    String[] str = {product.getResources()};
                    split = str;
                }
                split = product.getResources().split(",");
                //循环判断图片是否违规
                for (String s : split) {
                    if (!BaiduAuditUtils.ImgCensor(s)) {
                        sb.append("上传的服务图片违规了，服务图片的地址是:").append(product.getResources()).append(";");
                    }
                }
            }
            if (sb.length() > 0) {
                productOnlineAuditLog.setAuditTime(date);
                productOnlineAuditLog.setProductId(product.getId());
                productOnlineAuditLog.setNote(sb.toString());
                productOnlineAuditLog.setState(1);
                productOnlineAuditLogMapper.add(productOnlineAuditLog);
                continue;
            }

            //不违规创建html页面
            FreemarkerUtil.createFreemark(path, ids);
            product.setState(1L);
            product.setOnsaletime(date);
            productMapper.update(product);
        }
        ;
    }

    @Override
    public void offsaleProduct(List<Long> ids) {
        //批量下架
        //修改下架时间
        Date date = new Date();
        List<Product> products = getProducts(ids, 1L);
        ProductOnlineAuditLog productOnlineAuditLog = new ProductOnlineAuditLog();
        products.forEach(product -> {
            product.setState(0L);
            product.setOffsaletime(date);
            productMapper.update(product);


            productOnlineAuditLog.setAuditTime(date);
            productOnlineAuditLog.setProductId(product.getId());
            productOnlineAuditLog.setNote("下架");
            productOnlineAuditLog.setState(0);
            productOnlineAuditLogMapper.add(productOnlineAuditLog);
        });
        FreemarkerUtil.delFreemark(path,ids);
    }

    /**
     * 交易成功的订单
     * @param query
     * @return
     */
    @Override
    public PageList<ProductStaycheck> finish(OrderProductQuery query) {
        List<OrderProduct> orderProducts = orderProductMapper.queryByPage(query);
        //查询所有订单成功交易
        List<Long> collect = orderProducts.stream().map(OrderProduct::getProductId).collect(Collectors.toList());
        //查询店铺中的单子
        List<ProductStaycheck> staychecks = new ArrayList<>();
        collect.forEach(id->{
            List<ProductStaycheck> productId = productStaycheckMapper.findByProductId(id);
            staychecks.addAll(productId);
        });
        staychecks.forEach(productStaycheck -> {
            productStaycheck.setUser(userMapper.findById(productStaycheck.getUserId()));
        });

        Integer total = collect.size();
        //查询已完成的数据
        return new PageList<>(staychecks,total);
    }

    private List<Product> getProducts(List<Long> ids, Long state) {
        //传入的数据进行判断如果是已经下架了的id就不管
        List<Long> allids = ids.stream().filter(id -> productMapper.findById(id).getState() == state).collect(Collectors.toList());
        //通过id和对象存到，map中
        Map<Long, Product> promap = allids.stream().collect(Collectors.toMap(id -> id, id -> productMapper.findById(id)));
        //通过id获取对象
        List<Product> Productlist = allids.stream().map(id -> promap.get(id)).collect(Collectors.toList());
        return Productlist;
    }

}
